﻿namespace Vdc.Interface
{
    using Vdc.Interface.Design;
    using Vdc.Interface.HtmlControls;
    using Vdc.Interface.Interfaces;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;

    [PersistChildren(false), ParseChildren(true, "Items"), Designer(typeof(VdcDropDownListDesigner), typeof(IDesigner))]
    public class VdcDropDownList : DropDownList, IPostBackDataHandler, IPostBackEventHandler, IVdcControl
    {
        private static Hashtable _availableClientIds = new Hashtable();
        private VdcDropDownListCssSettings _cssSettings = new VdcDropDownListCssSettings();
        private string clientObjectID;
        private VdcDropDownListClientSideEvents clientSideEvents = new VdcDropDownListClientSideEvents();
        private VdcUl containerBodyContent;
        private VdcDiv content;
        protected string cssClassPrefix = "ob_iDdl";
        private List<HtmlLink> htmlLinksAddedToHead;
        private bool itemsAddedToContainer;
        protected VdcDiv itemsContainer;
        protected VdcDiv mainContainer = new VdcDiv();
        internal ScriptManagerHelper MyScriptManager;
        private Literal scriptContainerContent;
        protected HtmlInputHidden selectedIndexStorage;
        protected int selectedItemIndex;
        protected HtmlInputHidden selectedValueStorage;
        protected TextBox textBox;
        private VdcDiv topLeft;
        private VdcDiv topRight;

        protected virtual void AddItemsToItemsContainer()
        {
            this.containerBodyContent.Controls.Clear();
            this.selectedItemIndex = 0;
            for (int i = 0; i < this.Items.Count; i++)
            {
                VdcLi child = new VdcLi();
                this.containerBodyContent.Controls.Add(child);
                VdcB tb = new VdcB();
                child.Controls.Add(tb);
                Literal literal = new Literal();
                tb.Controls.Add(literal);
                literal.Text = VdcEncoder.HtmlEncode(this.Items[i].Text);
                VdcI ti = new VdcI();
                child.Controls.Add(ti);
                Literal literal2 = new Literal();
                ti.Controls.Add(literal2);
                literal2.Text = VdcEncoder.HtmlEncode(this.Items[i].Value);
                if (this.Items[i].Selected)
                {
                    this.selectedItemIndex = i;
                }
            }
            if (this.Items.Count == 0)
            {
                this.selectedItemIndex = -1;
            }
            this.itemsAddedToContainer = true;
        }

        protected override void CreateChildControls()
        {
            if (string.IsNullOrEmpty(this.Width.ToString()))
            {
                this.Width = Unit.Pixel(150);
            }
            this.mainContainer.ID = this.GetMainContainerID();
            this.mainContainer.Width = this.Width;
            this.mainContainer.CssClass = this.Enabled ? this.CssSettings.TopContainer_Normal : this.CssSettings.TopContainer_Disabled;
            this.CreateTopContainer();
            this.CreateItemsContainer();
            this.CreateSelectedValueStorage();
            this.CreateSelectedIndexStorage();
            VdcControlFactory.CreateChildControls(this);
            if (VdcControlFactory.IsDesignTimeRender(this))
            {
                this.mainContainer.Style["float"] = "left";
                if (string.IsNullOrEmpty(this.FolderStyle))
                {
                    this.topLeft.Style["background-image"] = VdcControlFactory.GetEmbeddedImageUrl(this, "horizontal.png");
                    this.topRight.Style["background-image"] = VdcControlFactory.GetEmbeddedImageUrl(this, "horizontal.png");
                    this.content.Style["background-image"] = VdcControlFactory.GetEmbeddedImageUrl(this, "vertical.png");
                }
                this.textBox.Style["display"] = "none";
            }
            base.CreateChildControls();
        }

        internal virtual VdcDiv CreateDiv(Control container, string cssClass)
        {
            VdcDiv child = new VdcDiv
            {
                CssClass = cssClass
            };
            container.Controls.Add(child);
            return child;
        }

        protected virtual void CreateItemsContainer()
        {
            this.itemsContainer = new VdcDiv();
            this.itemsContainer.ID = this.GetItemsContainerID();
            this.itemsContainer.CssClass = this.CssSettings.ItemsContainer;
            this.itemsContainer.Width = this.MenuWidth;
            this.itemsContainer.Style["display"] = "none";
            this.CreateItemsContainerHeader();
            this.CreateItemsContainerBody();
            this.CreateItemsContainerFooter();
            this.mainContainer.Controls.Add(this.itemsContainer);
        }

        protected virtual void CreateItemsContainerBody()
        {
            VdcDiv container = this.CreateDiv(this.itemsContainer, this.cssClassPrefix + "ICB");
            VdcDiv div2 = this.CreateDiv(container, this.cssClassPrefix + "ICBL");
            this.CreateDiv(div2, this.cssClassPrefix + "ICBLI");
            this.containerBodyContent = new VdcUl();
            container.Controls.Add(this.containerBodyContent);
            this.containerBodyContent.CssClass = this.cssClassPrefix + "ICBC";
            VdcDiv div3 = this.CreateDiv(container, this.cssClassPrefix + "ICBR");
            this.CreateDiv(div3, this.cssClassPrefix + "ICBRI");
            this.containerBodyContent.Height = this.Height;
            this.containerBodyContent.Style["min-height"] = this.Height.ToString();
            if (((this.DataSource == null) && string.IsNullOrEmpty(this.DataSourceID)) || !this.itemsAddedToContainer)
            {
                this.AddItemsToItemsContainer();
            }
        }

        protected virtual void CreateItemsContainerFooter()
        {
            VdcDiv container = this.CreateDiv(this.itemsContainer, this.cssClassPrefix + "ICF");
            this.CreateDiv(container, this.cssClassPrefix + "ICFCL");
            this.CreateDiv(container, this.cssClassPrefix + "ICFCM");
            this.CreateDiv(container, this.cssClassPrefix + "ICFCR");
        }

        protected virtual void CreateItemsContainerHeader()
        {
            VdcDiv container = this.CreateDiv(this.itemsContainer, this.cssClassPrefix + "ICH");
            this.CreateDiv(container, this.cssClassPrefix + "ICHCL");
            this.CreateDiv(container, this.cssClassPrefix + "ICHCM");
            this.CreateDiv(container, this.cssClassPrefix + "ICHCR");
        }

        protected virtual void CreateSelectedIndexStorage()
        {
            this.selectedIndexStorage = new HtmlInputHidden();
            this.selectedIndexStorage.ID = this.GetSelectedIndexStorageID();
            this.mainContainer.Controls.Add(this.selectedIndexStorage);
        }

        protected virtual void CreateSelectedValueStorage()
        {
            this.selectedValueStorage = new HtmlInputHidden();
            this.selectedValueStorage.ID = this.GetSelectedValueStorageID();
            this.mainContainer.Controls.Add(this.selectedValueStorage);
        }

        protected virtual void CreateTopContainer()
        {
            VdcDiv container = this.CreateDiv(this.mainContainer, "");
            container.ToolTip = this.ToolTip;
            this.topLeft = this.CreateDiv(container, this.CssSettings.TopContainer_LeftSide);
            this.topRight = this.CreateDiv(container, this.CssSettings.TopContainer_RightSide);
            this.content = this.CreateDiv(container, this.CssSettings.TopContainer_Content);
            this.textBox = VdcCloner.CloneDropDownListToTextBox(this);
            this.textBox.ID = this.GetTextBoxID();
            this.textBox.ReadOnly = true;
            this.textBox.CssClass = this.CssSettings.InputElement;
            this.textBox.Text = "";
            this.textBox.Attributes["autocomplete"] = "off";
            this.content.Controls.Add(this.textBox);
        }

        public override void DataBind()
        {
            if (!this.AppendDataBoundItems && ((this.DataSource != null) || !string.IsNullOrEmpty(this.DataSourceID)))
            {
                this.Items.Clear();
            }
            base.DataBind();
            if (this.containerBodyContent != null)
            {
                this.AddItemsToItemsContainer();
            }
        }

        protected virtual string GetEmbeddedStyleSheetLink()
        {
            return GetLinkToEmbeddedStyleSheet();
        }

        protected virtual string GetItemsContainerID()
        {
            return ("ob_iDdl" + this.ClientObjectID + "ItemsContainer");
        }

        protected virtual string GetItemsInnerTableID()
        {
            return ("ob_iDdl" + this.ClientObjectID + "ItemsInCont");
        }

        public static string GetLinkToEmbeddedStyleSheet()
        {
            return "Vdc.Interface.VdcDropDownList.resources.styles.black_glass.style.css";
        }

        protected virtual string GetMainContainerID()
        {
            return ("ob_iDdl" + this.ClientObjectID + "MainContainer");
        }

        protected virtual string GetSelectedIndexStorageID()
        {
            return ("ob_iDdl" + this.ClientObjectID + "SIS");
        }

        protected virtual string GetSelectedValueStorageID()
        {
            return this.UniqueID;
        }

        protected virtual string GetTextBoxID()
        {
            return ("ob_iDdl" + this.ClientObjectID + "TB");
        }

        protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            return base.LoadPostData(postDataKey, postCollection);
        }

        string IVdcControl.CreateClientScript(bool createOnlyClientObject)
        {
            return this.RenderClientScript(createOnlyClientObject);
        }

        void IVdcControl.ForceCreateChildControls()
        {
            this.CreateChildControls();
        }

        protected override void OnInit(EventArgs e)
        {
            this.MyScriptManager = new ScriptManagerHelper(this);
            base.OnInit(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            VdcControlFactory.RegisterClientScripts(this, null, null);
            base.OnPreRender(e);
        }

        public void RaisePostBackEvent(string eventArgument)
        {
        }

        protected override void RaisePostDataChangedEvent()
        {
            base.RaisePostDataChangedEvent();
        }

        public static void RegisterClientScripts(Control control)
        {
            ScriptManagerHelper helper = new ScriptManagerHelper(control);
            if (!helper.IsClientScriptIncludeRegistered("VdcCore"))
            {
                helper.RegisterClientScriptInclude("VdcCore", control.Page.ClientScript.GetWebResourceUrl(typeof(VdcDropDownList), "Vdc.Interface.VdcCore.resources.scripts.VdcCore.min.js"));
            }
            if (!helper.IsClientScriptIncludeRegistered("VdcControlFactory"))
            {
                helper.RegisterClientScriptInclude("VdcControlFactory", control.Page.ClientScript.GetWebResourceUrl(typeof(VdcDropDownList), "Vdc.Interface.VdcCore.resources.scripts.VdcControlFactory.min.js"));
            }
            if (!helper.IsClientScriptIncludeRegistered("VdcDropDownList"))
            {
                helper.RegisterClientScriptInclude("VdcDropDownList", control.Page.ClientScript.GetWebResourceUrl(typeof(VdcDropDownList), "Vdc.Interface.VdcDropDownList.resources.scripts.VdcDropDownList.min.js"));
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            this.EnsureChildControls();
            VdcControlFactory.Render(this, writer);
        }

        protected virtual string RenderClientScript(bool createOnlyClientObject)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(" if(typeof(" + this.ClientObjectID + ")!='undefined'){if(typeof(" + this.ClientObjectID + ".destruct)=='function'){" + this.ClientObjectID + ".destruct();}}");
            if (!createOnlyClientObject)
            {
                builder.Append("var " + this.ClientObjectID + ";");
                builder.Append("function initVdcDropDownList__" + this.ClientObjectID + "(attempts){ ");
                builder.Append("if(typeof(vdcDdlJSLoaded) == \"undefined\" || typeof(Vdc.Interface.VdcDropDownList) == \"undefined\") {if(attempts<30){window.setTimeout(\"initVdcDropDownList__" + this.ClientObjectID + "(\" + (attempts+1) + \")\", 500);}else{alert(\"There was a problem referencing DropDownList javascript files.  Please contact vdccontrol@gmail.com for support.\");}return;}");
                builder.Append("try{");
            }
            builder.Append(this.ClientObjectID + " = new Vdc.Interface.VdcDropDownList(");
            builder.Append("\"" + this.UniqueID + "\",");
            builder.Append("\"" + this.ClientObjectID + "\",");
            builder.Append("\"" + this.mainContainer.ClientID + "\",");
            builder.Append("\"" + this.itemsContainer.ClientID + "\",");
            builder.Append("\"" + this.textBox.ClientID + "\",");
            builder.Append("\"" + this.selectedValueStorage.ClientID + "\",");
            builder.Append("\"" + this.selectedIndexStorage.ClientID + "\",");
            builder.Append(this.selectedItemIndex.ToString() + ",");
            builder.Append("\"" + this.Width.ToString() + "\",");
            builder.Append("\"" + this.Height.ToString() + "\",");
            builder.Append("\"" + this.MenuWidth.ToString() + "\",");
            builder.Append(this.Enabled.ToString().ToLower() + ",");
            builder.Append((!string.IsNullOrEmpty(this.ClientSideEvents.OnSelectedIndexChanged) ? this.ClientSideEvents.OnSelectedIndexChanged : "null") + ",");
            builder.Append("null,");
            builder.Append(this.AutoPostBack.ToString().ToLower() + ",");
            if (!this.AutoPostBack)
            {
                builder.Append("null,");
            }
            else
            {
                builder.Append("function() {" + this.Page.ClientScript.GetPostBackEventReference(this, this.UniqueID) + "},");
            }
            builder.Append(this.CssSettings.SerializeToJSON() + ",");
            builder.Append("false,");
            builder.Append("true,");
            builder.Append("0,");
            builder.Append("\"\",");
            builder.Append("\"" + this.ControlsToEnable + "\",");
            builder.Append("\"" + this.ControlsToDisable + "\",");
            builder.Append("\"" + this.DisablingValues.Replace("\"", "\\\"") + "\",");
            builder.Append("\"" + this.EnablingValues.Replace("\"", "\\\"") + "\",");
            builder.Append(createOnlyClientObject.ToString().ToLower());
            builder.Append(");");
            if (!createOnlyClientObject)
            {
                builder.Append("return " + this.ClientObjectID + ";");
                builder.Append("}catch(e){alert(\"There was an error initializing DropDownList with ID " + this.ClientObjectID + ".\\n\\n\" + e.message + \"\\n\\nPlease contact vdcontrol@gmail.com for help.\");}}");
                builder.Append(" initVdcDropDownList__" + this.ClientObjectID + "(0); ");
            }
            return builder.ToString();
        }

        protected string ClientObjectID
        {
            get
            {
                if (string.IsNullOrEmpty(this.clientObjectID))
                {
                    this.clientObjectID = VdcControlFactory.GetClientObjectID(this);
                }
                return this.clientObjectID;
            }
            set
            {
                this.clientObjectID = value;
            }
        }

        [Category("Client-Side Events"), Bindable(true), PersistenceMode(PersistenceMode.InnerProperty), Description("Property used to define the Client-Side Events."), NotifyParentProperty(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public VdcDropDownListClientSideEvents ClientSideEvents
        {
            get
            {
                return this.clientSideEvents;
            }
            set
            {
                this.clientSideEvents = value;
            }
        }

        [Description("Gets or sets a value indicating the list of controls that will be disabled when the selection is changed."), Bindable(true)]
        public string ControlsToDisable
        {
            get
            {
                object obj2 = this.ViewState["ControlsToDisable"];
                if (obj2 != null)
                {
                    return obj2.ToString();
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["ControlsToDisable"] = value;
            }
        }

        [Bindable(true), Description("Gets or sets a value indicating the list of controls that will be enabled when the selection is changed.")]
        public string ControlsToEnable
        {
            get
            {
                object obj2 = this.ViewState["ControlsToEnable"];
                if (obj2 != null)
                {
                    return obj2.ToString();
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["ControlsToEnable"] = value;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), NotifyParentProperty(true), Bindable(true), Category("CSS Settings"), Description("Property used to define the CSS Settings.")]
        public virtual VdcDropDownListCssSettings CssSettings
        {
            get
            {
                return this._cssSettings;
            }
            set
            {
                this._cssSettings = value;
            }
        }

        [Bindable(true), Description("Gets or sets a list of item values that when selected will disable the controls specified with the ControlsToDisable property.")]
        public string DisablingValues
        {
            get
            {
                object obj2 = this.ViewState["DisablingValues"];
                if (obj2 != null)
                {
                    return obj2.ToString();
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["DisablingValues"] = value;
            }
        }

        [Description("Gets or sets a list of item values that when selected will enable the controls specified with the ControlsToEnable property."), Bindable(true)]
        public string EnablingValues
        {
            get
            {
                object obj2 = this.ViewState["EnablingValues"];
                if (obj2 != null)
                {
                    return obj2.ToString();
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["EnablingValues"] = value;
            }
        }

        [Description("The folder containing the css stylesheet."), Bindable(true)]
        public string FolderStyle
        {
            get
            {
                object obj2 = this.ViewState["FolderStyle"];
                if (obj2 != null)
                {
                    return obj2.ToString();
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["FolderStyle"] = value;
            }
        }

        [Bindable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public override ListItemCollection Items
        {
            get
            {
                return base.Items;
            }
        }

        [Bindable(true), Description("The width of the drop down menu.")]
        public Unit MenuWidth
        {
            get
            {
                object obj2 = this.ViewState["MenuWidth"];
                if (obj2 != null)
                {
                    return (Unit) obj2;
                }
                return this.Width;
            }
            set
            {
                this.ViewState["MenuWidth"] = value;
            }
        }

        Hashtable IVdcControl.AvailableClientIds
        {
            get
            {
                return _availableClientIds;
            }
        }

        VdcDiv IVdcControl.Container
        {
            get
            {
                return this.mainContainer;
            }
        }

        bool IVdcControl.HasChildControlsCreated
        {
            get
            {
                return base.ChildControlsCreated;
            }
        }

        List<HtmlLink> IVdcControl.HtmlLinksAddedToHead
        {
            get
            {
                if (this.htmlLinksAddedToHead == null)
                {
                    this.htmlLinksAddedToHead = new List<HtmlLink>();
                }
                return this.htmlLinksAddedToHead;
            }
        }

        bool IVdcControl.IsDesignTimeRender
        {
            get
            {
                return base.DesignMode;
            }
        }

        string IVdcControl.LinkToEmbeddedStyleSheet
        {
            get
            {
                return this.GetEmbeddedStyleSheetLink();
            }
        }

        Literal IVdcControl.ScriptContainerContent
        {
            get
            {
                return this.scriptContainerContent;
            }
            set
            {
                this.scriptContainerContent = value;
            }
        }

        ScriptManagerHelper IVdcControl.ScriptManager
        {
            get
            {
                return this.MyScriptManager;
            }
            set
            {
                this.MyScriptManager = value;
            }
        }

        bool IVdcControl.StyleSheetReferenceAdded
        {
            get
            {
                return HttpContext.Current.Items.Contains("vdcDropDownList_StyleSheetAdded");
            }
            set
            {
                if (value)
                {
                    HttpContext.Current.Items.Add("vdcDropDownList_StyleSheetAdded", true);
                }
                else
                {
                    HttpContext.Current.Items.Remove("vdcDropDownList_StyleSheetAdded");
                }
            }
        }
    }
}

